<template>
  <div class="health-analysis-container">
    <!-- 页面标题：隐藏默认返回箭头 -->
    <el-page-header style="margin-bottom: 20px;">
      <template v-slot:content>
        设备健康度分析
      </template>
    </el-page-header>

    <!-- 健康等级分布 - 卡片 + 图表 -->
    <el-row :gutter="20">
      <el-col :span="10">
        <el-card shadow="hover" class="stat-card">
          <div slot="header">
            <span>设备健康等级分布</span>
          </div>
          <div class="chart-box">
            <!-- 环形图：正常/停运/故障 -->
            <div id="healthPie" style="width: 100%; height: 220px;"></div>
          </div>
          <div class="stat-desc">
            正常: {{ healthStats.normal }} 台 | 停运: {{ healthStats.stop }} 台 | 故障: {{ healthStats.fault }} 台
          </div>
        </el-card>
      </el-col>

      <!-- 高风险设备清单 -->
      <el-col :span="14">
        <el-card shadow="hover" class="stat-card">
          <div slot="header">
            <span>高风险设备</span>
            <el-input
                v-model="searchId"
                placeholder="输入设备ID查询"
                style="width: 200px; margin-right: 10px;"
            />
            <el-button type="primary" size="mini" @click="fetchRiskDeviceList">查询</el-button>
            <el-button type="primary" size="mini" @click="refreshRiskList">刷新</el-button>
          </div>
          <el-table
              :data="tableData"
              border
              style="width: 100%; margin-top: 10px;"
              height="300"
              @row-click="handleRowClick"
          >
            <el-table-column prop="deviceId" label="设备ID" width="100"></el-table-column>
            <el-table-column prop="deviceName" label="设备名称" width="120"></el-table-column>
            <el-table-column prop="deviceCode" label="设备编码" width="100"></el-table-column>
            <el-table-column prop="riskLevel" label="风险等级" width="100"></el-table-column>
            <el-table-column prop="riskFactor" label="风险因子" min-width="180"></el-table-column>
          </el-table>
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[5]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              style="margin-top: 10px; text-align: right;"
          >
          </el-pagination>
          <!-- 设备详细信息弹窗 -->
          <el-dialog title="设备详细信息" :visible.sync="dialogVisible" width="50%">
            <el-table :data="selectedDeviceDetail">
              <el-table-column
                  label="字段"
                  prop="field"
                  min-width="120"
              />
              <el-table-column
                  label="值"
                  prop="value"
                  min-width="200"
              />
            </el-table>
          </el-dialog>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { Message } from 'element-ui';
import { api } from "@/api";

export default {
  name: 'DeviceHealthAnalysis',
  data() {
    return {
      healthStats: {
        normal: 0,
        stop: 0,
        fault: 0
      },
      riskDeviceList: [],
      tableData: [],
      searchId: '',
      currentPage: 1,
      pageSize: 5,
      total: 0,
      dialogVisible: false,
      selectedDeviceDetail: [],
      pieChart: null // 初始化图表实例
    };
  },
  mounted() {
    this.initCharts();
    this.fetchHealthStats();
    this.fetchRiskDeviceList();
  },
  methods: {
    initCharts() {
      this.pieChart = echarts.init(document.getElementById('healthPie'));
    },
    async fetchHealthStats() {
      try {
        const res = await api.device.gethealthStats();
        this.healthStats = res.data;
        this.renderPieChart();
      } catch (error) {
        Message.error('获取健康等级分布数据失败：' + error.message);
      }
    },
    renderPieChart() {
      this.pieChart.setOption({
        title: { text: '', left: 'center' },
        tooltip: { trigger: 'item' },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: ['正常', '停运', '故障']
        },
        series: [
          {
            name: '健康等级',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: true,
              position: 'outside'
            },
            data: [
              { value: this.healthStats.normal, name: '正常' },
              { value: this.healthStats.stop, name: '停运' },
              { value: this.healthStats.fault, name: '故障' }
            ]
          }
        ]
      });
    },
    async fetchRiskDeviceList() {
      try {
        const res = await api.device.getHighRisk(this.searchId);
        this.riskDeviceList = res.data;
        this.total = this.riskDeviceList.length;
        this.handleCurrentChange(1);
      } catch (error) {
        Message.error('获取高风险设备失败：' + error.message);
      }
    },
    refreshRiskList() {
      this.searchId = '';
      this.fetchRiskDeviceList();
      Message.success('高风险设备列表已刷新');
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.handleCurrentChange(this.currentPage);
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      const startIndex = (val - 1) * this.pageSize;
      const endIndex = startIndex + this.pageSize;
      this.tableData = this.riskDeviceList.slice(startIndex, endIndex);
    },
    async handleRowClick(row) {
      const fieldMap = {
        deviceId: '设备ID',
        deviceCode: '设备编码',
        deviceName: '设备名称',
        alarmCount: '报警次数',
        latestAlarmTime: '最近报警时间',
        riskLevel: '风险等级',
        riskFactor: '风险因子',
        createTime: '创建时间',
        updateTime: '更新时间'
      };
      try {
        const res = await api.device.getHighRisk(row.deviceId);
        const detailObj = res.data && res.data.length > 0 ? res.data[0] : {};
        this.selectedDeviceDetail = Object.entries(detailObj).map(([field, value]) => ({
          field: fieldMap[field] || field,
          value
        }));
        this.dialogVisible = true;
      } catch (error) {
        Message.error('获取设备详细信息失败：' + error.message);
      }
    }
  },
  beforeDestroy() {
    if (this.pieChart instanceof echarts.ECharts) {
      this.pieChart.dispose();
    }
  }
};
</script>

<style scoped>
.health-analysis-container {
  padding: 20px;
}
.stat-card {
  height: 100%;
}
.chart-box {
  display: flex;
  justify-content: center;
  align-items: center;
}
.stat-desc {
  text-align: center;
  margin-top: 10px;
  color: #666;
}

/* 隐藏 el-page-header 的返回箭头 */
.el-page-header__left {
  display: none !important;
}
</style>